import { HttpException, HttpStatus, Injectable } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Question, QuestionDocument } from './schemas/question.schema';
import mongoose, { DeleteResult, Model } from 'mongoose';
import { QuestionDTO } from './dto/question.dto';
import { nanoid } from 'nanoid';
@Injectable()
export class QuestionService {
  constructor(
    //依赖注入
    @InjectModel(Question.name)
    private readonly questionModel: Model<QuestionDocument>,
  ) {}

  //创建问卷
  async createOne(question: QuestionDTO, author: string) {
    try {
      const newQuestion = new this.questionModel({
        ...question,
        author,
      });
      return await newQuestion.save();
    } catch (e) {
      throw new HttpException(e, HttpStatus.BAD_REQUEST);
    }
  }
  //根据id查询问卷
  async findOne(id: string) {
    const res = await this.questionModel.findById(id);

    return res;
  }
  //通过id更新问卷
  async updateOne(id: string, question: QuestionDTO, author: string) {
    return await this.questionModel.updateOne(
      {
        _id: id,
        author,
      },
      question,
    );
  }
  //通过id删除问卷
  async deleteOne(id: string, author: string) {
    return await this.questionModel.findOneAndDelete({ _id: id, author });
  }

  //删除多个
  async deleteMany(ids: string[], author: string): Promise<DeleteResult> {
    const res = await this.questionModel.deleteMany({
      _id: { $in: ids },
      author,
    });
    return res;
  }

  // 通过条件查询问卷
  async find({ page, keyword, pageSize, isStar, isDeleted, author }) {
    let query = {};
    if (keyword) {
      query = {
        $or: [
          { title: new RegExp(keyword, 'i') },
          { desc: new RegExp(keyword, 'i') },
        ],
      };
    }

    query = {
      ...query,
      author,
      isDeleted,
      isStar,
    };

    const total = await this.questionModel.countDocuments(query);
    const questions = await this.questionModel
      .find(query)
      .sort({ _id: -1 }) //逆序
      .skip((page - 1) * pageSize)
      .limit(pageSize)
      .exec();
    return {
      total,
      questions,
    };
  }

  // 复制问卷
  async dulplicate(id: string, author: string) {
    const question = await this.questionModel.findById(id);
    const newQuestion = new this.questionModel({
      ...question?.toObject(),
      _id: new mongoose.Types.ObjectId(),
      title: `${question?.title}-副本`,
      author,
      isPublished: false,
      isStar: false,
      componentList: question?.componentList.map((item) => ({
        ...item,
        fe_id: nanoid(),
      })),
    });

    return await newQuestion.save();
  }
}
